using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DualCameraApp.Models;
using System;
using System.Collections.ObjectModel;
using System.Linq;

namespace DualCameraApp.ViewModels;

public partial class MainWindowViewModel : ObservableObject
{
    [ObservableProperty]
    private ObservableCollection<CameraViewModel> _cameras = new();
    
    [ObservableProperty]
    private string _statusMessage = "就绪";
    
    public MainWindowViewModel()
    {
        InitializeCameras();
    }
    
    private void InitializeCameras()
    {
        var availableCameras = CameraService.GetAvailableCameras();
        
        // if (availableCameras.Count < 2)
        // {
        //     StatusMessage = $"找到 {availableCameras.Count} 个摄像头，需要至少2个摄像头";
        //     return;
        // }
        
        // 使用前两个摄像头
        for (int i = 0; i < availableCameras.Count; i++)
        {
            var cameraVM = new CameraViewModel(availableCameras[i]);
            Cameras.Add(cameraVM);
        }
        
        StatusMessage = $"已加载 {Cameras.Count} 个摄像头";
    }
    
    [RelayCommand]
    private void StartAllCameras()
    {
        foreach (var camera in Cameras)
        {
            camera.StartCamera();
        }
        StatusMessage = "所有摄像头已启动";
    }
    
    [RelayCommand]
    private void StopAllCameras()
    {
        foreach (var camera in Cameras)
        {
            camera.StopCamera();
        }
        StatusMessage = "所有摄像头已停止";
    }
    
    [RelayCommand]
    private void CaptureAll()
    {
        foreach (var camera in Cameras)
        {
            camera.CaptureImage();
        }
        StatusMessage = "所有摄像头已拍照";
    }
    
    [RelayCommand]
    private void StartRecordingAll()
    {
        foreach (var camera in Cameras)
        {
            if (!camera.IsRecording && camera.IsCameraActive)
            {
                camera.StartRecording();
            }
        }
        StatusMessage = "所有摄像头开始录制";
    }
    
    [RelayCommand]
    private void StopRecordingAll()
    {
        foreach (var camera in Cameras)
        {
            if (camera.IsRecording)
            {
                camera.StopRecording();
            }
        }
        StatusMessage = "所有摄像头停止录制";
    }
    
    [RelayCommand]
    private void RefreshCameras()
    {
        foreach (var camera in Cameras.ToList())
        {
            camera.Dispose();
        }
        Cameras.Clear();
        
        InitializeCameras();
    }
}